package com.han.controllers;

import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Random;

import javax.naming.NamingException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;

import com.han.bom.Exam;
import com.han.bom.ExamResponse;
import com.han.bom.MultipleChoice;
import com.han.bom.PracticeExam;
import com.han.bom.Question;
import com.han.bom.RealExam;
import com.han.bom.Student;
import com.han.dao.concrete.product.AnswerDAO;
import com.han.dao.concrete.product.ExamDAO;
import com.han.dao.concrete.product.ExamResponseDAO;
import com.han.dao.concrete.product.QuestionDAO;

/**
 * Servlet implementation class TakeExamServlet
 */
@WebServlet("/Student/TakeExamServlet")
public class TakeExamServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
    
	private Logger logger = Logger.getLogger(getClass().getName());
	
    /**
     * @see HttpServlet#HttpServlet()
     */
    public TakeExamServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		logger.info("Entered TakeExamServlet GET");
		HttpSession session = request.getSession();
		
		Student student = null;
		String examID = null;
//		String type=null;
		Exam exam = null;
		ExamDAO examdao = new ExamDAO();
		
		if(session.getAttribute("student")!=null){
			student = (Student)session.getAttribute("student");
		}
		else{
			request.setAttribute("msg", "Error!");
			request.setAttribute("type", "fail");
			
			RequestDispatcher rd = request.getRequestDispatcher("Login.jsp");
			rd.forward(request,response);
		}
		
		if(request.getParameter("examID")!=null){
			examID = request.getParameter("examID");
		}
		else{
			request.setAttribute("msg", "Error!");
			request.setAttribute("type", "fail");
			
			RequestDispatcher rd = request.getRequestDispatcher("Student.jsp");
			rd.forward(request,response);
		}
		
//		if(request.getParameter("type")!=null){
//			type = request.getParameter("type");
//		}
//		else{
//			
//		}
		
		if(student!=null && examID !=null){
			
			student.setExamsToTake(new ArrayList<Exam>());
			student.setExamAnswers(new ArrayList<ExamResponse>());
			
			try {
				exam = examdao.retrieveExamById(examID);
			} catch (ClassNotFoundException e) {
				logger.error(e.getMessage(), e);
				e.printStackTrace();
			} catch (SQLException e) {
				logger.error(e.getMessage(), e);
				e.printStackTrace();
			} catch (NamingException e) {
				logger.error(e.getMessage(), e);
				e.printStackTrace();
			}
			
			if(exam instanceof RealExam){
				if(!((RealExam) exam).isActivated()){
					response.sendRedirect("Home.jsp?msg=Exam+is+locked");
				}
			}
			
			AnswerDAO answerdao = new AnswerDAO();
			QuestionDAO questiondao = new QuestionDAO();
			
			ArrayList<Question> questions = null;
			try {
				questions = questiondao.retrieveQuestionsbyExam(examID);
				
				for(Question question: questions){
					ArrayList<String> choices = answerdao.retrieveAnswersByQuestion(question.getQuestionID());
					question.setAnswer(choices.get(0));
					
					if(question instanceof MultipleChoice){
						Collections.sort(choices);
					}
					else{
						Collections.sort(choices);
						Collections.reverse(choices);
					}
					
					question.setQuestion(question.getQuestion().replace(" ","&nbsp;"));
					question.setQuestion(question.getQuestion().replace("\n","<br />"));
					
					question.setChoices(choices);
				}
			} catch (ClassNotFoundException e1) {
				logger.error(e1.getMessage(), e1);
				e1.printStackTrace();
			} catch (SQLException e1) {
				logger.error(e1.getMessage(), e1);
				e1.printStackTrace();
			} catch (NamingException e) {
				logger.error(e.getMessage(), e);
				e.printStackTrace();
			}
			
			long seed = System.nanoTime();
			Collections.shuffle(questions, new Random(seed));
			
			exam.setQuestions(questions);
			student.getExamsToTake().add(exam);
			
			ExamResponseDAO examresponsedao = new ExamResponseDAO();
			
			if(exam instanceof PracticeExam){
				try {
					((PracticeExam) exam).setTimesTaken(examresponsedao.retrieveResponseCountByStudentAndExam(student.getUserID(), exam.getExamID())+1);
				} catch (ClassNotFoundException e) {
					logger.error(e.getMessage(), e);
					e.printStackTrace();
				} catch (SQLException e) {
					logger.error(e.getMessage(), e);
					e.printStackTrace();
				} catch (NamingException e) {
					logger.error(e.getMessage(), e);
					e.printStackTrace();
				}
			}
			
			student.takeExam(exam);
			
			try {
				examresponsedao.insertExamResponse(student,true);
				if(exam instanceof RealExam){
					examdao.removeStudentFromExam(student.getUserID(), exam.getExamID());
				}
			} catch (ClassNotFoundException e) {
				logger.error(e.getMessage(), e);
				e.printStackTrace();
			} catch (SQLException e) {
				logger.error(e.getMessage(), e);
				e.printStackTrace();
			} catch (NamingException e) {
				logger.error(e.getMessage(), e);
				e.printStackTrace();
			}
			
			RequestDispatcher rd = null;
			
			if(exam instanceof RealExam){
				exam.setDuration(exam.getDuration()*60);
				rd = request.getRequestDispatcher("Take_RealExam.jsp");
				
			}
			else{
				rd = request.getRequestDispatcher("Take_PracticeExam.jsp");
			}
			
			
			request.setAttribute("exam", exam);
			
			rd.forward(request,response);
		}
	
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

	
	}
}